
import qs from 'qs'

var functions = {
  /**
   * @name 判断传入地址的图片是否加载成功
   * @param {str} imgurl 
   * @param {function} callback 
   */
  imgLoad(imgurl, callback) {
    var img = new Image()
    img.src = imgurl
    if (callback) {
      callback()
    }
    return img.complete
  },

  /**
   * @name 倒计时
   * @param {int} time 
   * @param {function} callback 
   */
  countDown(time, callback) {
    var timeDown = setInterval(() => {
      // return time
      if (time == 0) {
        clearInterval(timeDown)
        if (callback) callback()
      } else {
        time--
      }
    }, 1000)
  },

  /**
   * @name 获取当前路由path
   * @param {*} vue 
   */
  getRouterPath(vue) {
    var routerPath = vue.$router.history.current.path
    return routerPath
  },

  /**
   * @name 获取当前路由中携带的参数，返回param或者返回全部的参数
   * @param {*} vue 
   * @param {str} param 
   */
  getRouterParams(vue, param) {
    if (param) {
      return vue.$router.history.current.params.param
    } else {
      return vue.$router.history.current.params
    }
  },


  getBacImg(vue) {
    return 'background:url(' + localStorage.getItem("homepageImg") + ');background-position-x:' + vue.$store.state.homePageBac.positionX + ';background-position-y:' + vue.$store.state.homePageBac.positionY + ';background-size:' + vue.$store.state.homePageBac.bacSize
  },


  getRightSize() {
    var size = Math.floor(Math.random(15, 20) * 500)
    if (size > 352) {
      return size
    } else {
      return _g.getRightSize()
    }
  },

  /**
   * @name 从array中获取符合的obj
   */
  getRightItem(array, key, value) {
    for (var item of array) {
      if (item[key] == value) {
        return item
      }
    }
  },

  /**
   * @name 添加入场动画
   * @param {*} optionClass 
   * @param {*} animationClass 
   * @param {*} time  时间间隔
   * @param {int} delay 统一延迟
   */
  addAnimation(optionClass, animationClass, time, delay) {
    var delay = delay || 0
    var array = document.querySelectorAll(optionClass)
    array.forEach((ele, index) => {
      setTimeout(() => {
        ele.classList.remove(animationClass)
      }, index * time + delay)
    });
  },


  changeTitle(title) {
    document.querySelector("title").innerText = title || "ssss"
  },


  /**
   * @name 公共的请求方法
   * @param {*} url 
   * @param {*} params 
   * @param {*} loading 显示加载中
   */
  async apiPost(url, params, loading) {
    var loading = loading || false
    var path = PATH + url
    var result = null
    _store.state.dialogs.loading.show = true

    if (localStorage.getItem("orgId") != "undefined" && localStorage.getItem("orgId") && params && !params.organizationId) {
      // params.organizationId=localStorage.getItem("orgId")
    }

    if (loading) { _store.state.dialogs.loading.show = false }

    try {
      await $axios.post(path, qs.stringify(params)).then(res => {
        result = res
        _store.state.dialogs.loading.show = false
      });
    }
    catch (err) {
      var errorinfo = "出问题了"
      switch (err.toString().split(" ").slice(-1)[0]) {
        case "404": errorinfo = "访问地址不正确"; break;
        case "500": errorinfo = "后台出错"; break;
      }
      _store.state.dialogs.alert.content = errorinfo
      _store.state.dialogs.alert.show = true
    }
    finally {
      _store.state.dialogs.loading.show = false
    }
    return await result ? result.data : null;
  },

  checkForm(formData, params) {
    var goal = true
    formData.forEach(ele => {
      ele.children.forEach(ele1 => {
        if (ele1.checked && !params[ele1.key]) {
          _store.state.dialogs.alert.content = ele1.label + " 不能为空"
          _store.state.dialogs.alert.show = true
          goal = false
        }
      })
    })

    return goal
  },

  toMessage(res) {
    var type = res.status == 0 ? "success" : "cancel"
    var content = res.msg || res.data || "暂时没有反馈信息15151515151"
    _store.state.dialogs.feedback.type = type
    _store.state.dialogs.feedback.content = content
    _store.state.dialogs.feedback.show = true
  },

  /**
   * @name {#} 将obj1合并到obj2中
   * @param {*} obj1 
   * @param {*} obj2 
   */
  assign(obj1, obj2) {
    var obj = obj2 || {}
    for (var key in obj1) {
      obj[key] = obj1[key]
    }
    return obj
  },

  /**
   * @name 异步同步化
   * @param {*} array 
   */
  async orderList(array) {
    for await (let item of array) {
      item()
    }
  },

  formatTime(time) {
    return new Date(time).getFullYear() + "-" + (new Date(time).getMonth() + 1) + "-" + new Date(time).getDate()
  },

  // exif.js 中用来获取图片信息的
  getPhotoOrientation(img) {
    var orient;
    EXIF.getData(img, function () {
      orient = EXIF.getTag(this, "Orientation");
    });
    return orient;
  },
  

  login(params) {
    var params = params || {
      code: "o2mBI0m7dsQEU8m_oVHb0ZByXup4",
      organizationId: "14",
    }
    sessionStorage.removeItem("userId")
    sessionStorage.removeItem("userName")
    sessionStorage.removeItem("userPhone")
    sessionStorage.removeItem("isUser")
    sessionStorage.removeItem("sessitionId")

    if (!sessionStorage.getItem("sessitionId") || TESTHERE) {
      _g.apiPost("Appuser/userLogin.do", params).then(res => {
        if (res.status) {
          _g.toMessage(res)
          return
        }
        _g.toMessage({ status: 0, msg: "登录成功" })
        sessionStorage.setItem("sessitionId", res.data.sessionId)
        document.cookie = "JSESSIONID=" + res.data.sessionId
        sessionStorage.setItem("userId", res.data.User.id)
        sessionStorage.setItem("userName", res.data.User.nickname)
        sessionStorage.setItem("userPhone", res.data.User.phone)
        sessionStorage.setItem("isUser", res.data.User.employeeId)
      })
    } else {
      _g.toMessage({ status: 1, msg: "已登录" })
    }
  },

  setShare(url) {
    var url =url || (backPath + "car_app/" + _store.state.path.slice(1))
    _g.apiPost("WXshare/wechatParam.do", { url }).then(res => {
      wx.config({
        debug: false,////生产环境需要关闭debug模式
        appId: res.appid,//appId通过微信服务号后台查看
        timestamp: res.timestamp,//生成签名的时间戳
        nonceStr: res.nonceStr,//生成签名的随机字符串
        signature: res.signature,//签名
        jsApiList: [//需要调用的JS接口列表
          'checkJsApi',//判断当前客户端版本是否支持指定JS接口
          'onMenuShareTimeline',//分享给好友
          'onMenuShareAppMessage'//分享到朋友圈
        ]
      });
      sessionStorage.setItem("setUrl", res.url)
      wx.ready(function () {
        var link = sessionStorage.getItem("setUrl")
        var imgUrl = "https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=903913314,1917087931&fm=200&gp=0.jpg"
        //分享朋友圈
        wx.onMenuShareTimeline({
          title: '赶快来看看！',
          link: link,
          imgUrl,// 自定义图标
          trigger: function (res) {
            // 不要尝试在trigger中使用ajax异步请求修改本次分享的内容，因为客户端分享操作是一个同步操作，这时候使用ajax的回包会还没有返回.
            //alert('click shared');
          },
          success: function (res) {
            //alert('shared success');
            //some thing you should do
          },
          cancel: function (res) {
            //alert('shared cancle');
          },
          fail: function (res) {
            //alert(JSON.stringify(res));
          }
        });
        //分享给好友
        wx.onMenuShareAppMessage({
          title: '赶快领取卡券！', // 分享标题
          desc: '领取卡券减上再减。', // 分享描述
          link: link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
          imgUrl, // 自定义图标
          type: 'link', // 分享类型,music、video或link，不填默认为link
          dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
          success: function () {
            // 用户确认分享后执行的回调函数
          },
          cancel: function () {
            // 用户取消分享后执行的回调函数
          }
        });
        wx.error(function (res) {
          alert(res.errMsg);
        });
      });
    })
  },


  /**
   * @name 拓展方法
   * @param {*} name 
   * @param {*} method 
   */
  fn(name, method) {
    if (!method) throw new Error("拓展方法未定义")
    if (Object.keys(this).includes(name)) throw new Error("方法名" + name + "重复")
    this[name] = method
  }

}

export default functions